import { MBErrorCode, MBProtocalType, MBSocketEvent } from "./mb_constants";
import MBCore from './mb_core'
import MBUtils from './mb_utils'
import MBQoS4ReciveDaemon from './mb_daemon_qos_recieve'
import MBAutoReLoginDaemon from './mb_daemon_auto_relogin'
import MBKeepAliveDaemon from './mb_daemon_keep_alive'
import MBQoS4SendDaemon from './mb_daemon_qos_send'
import MBSocketProvider from './mb_socket_provider'
import MBProtocalFactory from './mb_constants'
import MBDataSender from './mb_data_sender'

class MBDataReciever {

    handleProtocal(pFromServer: any) {
        if (pFromServer) {

            try {
                if (pFromServer.QoS) {
                    if (pFromServer.type === MBProtocalType.FROM_SERVER_TYPE_OF_RESPONSE$LOGIN
                        && JSON.parse(pFromServer.dataContent).code !== 0) {
                        if (MBCore.debugEnabled()) {
                            console.log("【BugFIX】这是服务端的登陆返回响应包，且服务端判定登陆失败(即code!=0)，本次无需发送ACK应答包！")
                        }
                    }
                    else {
                        if (MBQoS4ReciveDaemon.hasRecieved(pFromServer.fp)) {
                            if (MBCore.debugEnabled()) {
                                console.log("【QoS机制】" + pFromServer.fp + "已经存在于发送列表中，这是重复包，通知应用层收到该包罗！")
                            }
                            MBQoS4ReciveDaemon.addRecievedProtocal(pFromServer);
                            this.sendRecievedBack(pFromServer);
                            return;
                        }

                        MBQoS4ReciveDaemon.addRecievedProtocal(pFromServer);
                        this.sendRecievedBack(pFromServer);
                    }
                }

                // 真正的指令处理逻辑
                switch (pFromServer.type) {
                    // ** 收到通用数据
                    case MBProtocalType.FROM_CLIENT_TYPE_OF_COMMON$DATA: {
                        this.onRecievedCommonData(pFromServer);
                        break;
                    }
                    //** 收到服务反馈过来的心跳包
                    case MBProtocalType.FROM_SERVER_TYPE_OF_RESPONSE$KEEP$ALIVE: {
                        this.onServerResponseKeepAlive();
                        break;
                    }
                    //** 收到好友发过来的QoS应答包
                    case MBProtocalType.FROM_CLIENT_TYPE_OF_RECIVED: {
                        this.onMessageRecievedACK(pFromServer);
                        break;
                    }
                    // ** 收到服务端反馈过来的登陆完成信息
                    case MBProtocalType.FROM_SERVER_TYPE_OF_RESPONSE$LOGIN: {
                        this.onServerResponseLogined(pFromServer);
                        break;
                    }
                    // ** 服务端返回来过的错误消息
                    case MBProtocalType.FROM_SERVER_TYPE_OF_RESPONSE$FOR$ERROR: {
                        this.onServerResponseError(pFromServer);
                        break;
                    }
                    // ** 服务端发回来过的“重复登录被踢”消息
                    case MBProtocalType.FROM_SERVER_TYPE_OF_KICKOUT: {
                        this.onKickout(pFromServer);
                        break;
                    }
                    default: {
                        console.log("收到的服务端消息类型：" + pFromServer.getType() + "，但目前该类型客户端不支持解析和处理！")
                        break;
                    }
                }
            }
            catch (e) {
                console.log("处理消息的过程中发生了错误.", e)
            }
        }
        else {
            console.log("无效的pFromServer（" + pFromServer + "）！");
        }
    };

    onRecievedCommonData(pFromServer: any) {
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_ON_RECIEVE_MESSAGE, pFromServer);
    };

    onServerResponseKeepAlive() {
        if (MBCore.debugEnabled()) {
            console.log("收到服务端回过来的Keep Alive心跳响应包.")
        }

        MBCore.emit(MBSocketEvent.SOCKET_EVENT_PONG, null);
        MBKeepAliveDaemon.updateGetKeepAliveResponseFromServerTimstamp();
    };

    onMessageRecievedACK(pFromServer: any) {
        var theFingerPrint = pFromServer.dataContent;
        if (MBCore.debugEnabled()) {
            console.log("【QoS】收到" + pFromServer.from + "发过来的指纹为" + theFingerPrint + "的应答包.");
        }

        // 将收到的应答事件通知事件处理者
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_MESSAGE_BE_RECIEVED, theFingerPrint);

        // 【【C2C或C2S模式下的QoS机制4/4步：收到应答包时将包从发送QoS队列中删除】】
        MBQoS4SendDaemon.remove(theFingerPrint);
    };

    /**
     * 收到登陆响应包的处理逻辑。
     *
     * @param pFromServer {Protocal} 原始数据包
     */
    onServerResponseLogined(pFromServer: any) {
        var loginInfoRes = JSON.parse(pFromServer.dataContent);

        if (loginInfoRes.code === 0) {

            if (!MBCore.isLoginHasInit()) {
                console.log("首次登陆验证成功，firstLoginTime=" + loginInfoRes.firstLoginTime);
                MBCore.setCurrenetLoginInfo_firstLoginTime(loginInfoRes.firstLoginTime);
            }

            this.fireConnectedToServer();
        } else {
            console.log("登陆验证失败，错误码=" + loginInfoRes.code + "！");
            MBSocketProvider.closeLocalSocket();
            MBCore.setConnectedToServer(false);
        }
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_ON_LOGIN_RESPONSE, loginInfoRes);
    };

    onServerResponseError(pFromServer: any) {
        var errorRes = JSON.parse(pFromServer.dataContent);
        if (errorRes.errorCode === MBErrorCode.RESPONSE_FOR_UNLOGIN) {
        
            MBCore.setLoginHasInit(false);
            console.log("收到服务端的“尚未登陆”的错误消息，心跳线程将停止，请应用层重新登陆.");
            MBKeepAliveDaemon.stop();
            MBAutoReLoginDaemon.start(false);
        }
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_ON_ERROR_RESPONSE, errorRes);
    };

   
    onKickout(pFromServer:any) {
        if (MBCore.debugEnabled()){
            console.log("收到服务端发过来的“重复登录被踢”消息.");
        }
        MBCore.release();

        var kickoutInfo = JSON.parse(pFromServer.dataContent);
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_KICKOUT, kickoutInfo);
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_ON_LINK_CLOSE, -1);
    };


    fireConnectedToServer() {
        var that = this;
        MBCore.setLoginHasInit(true);
        MBAutoReLoginDaemon.stop();
        var networkConnectionLostCallBack=  ()=>{
            that.fireDisconnectedToServer();
        };
        MBKeepAliveDaemon.setNetworkConnectionLostCallback(networkConnectionLostCallBack);
        MBKeepAliveDaemon.start(false);
        MBQoS4SendDaemon.startup(true);
        MBQoS4ReciveDaemon.startup(true);
        MBCore.setConnectedToServer(true);
    };

    fireDisconnectedToServer() {
        MBCore.setConnectedToServer(false);
        MBSocketProvider.closeLocalSocket();
        MBQoS4ReciveDaemon.stop();
        MBCore.emit(MBSocketEvent.SOCKET_EVENT_ON_LINK_CLOSE, -1);
        MBAutoReLoginDaemon.start(true);// 建议：此参数可由true改为false，防止服务端重启等情况下，客户端立即重连等
    };
    sendRecievedBack(pFromServer:any) {
        if (pFromServer.fp) {
            var pForRecivedBack = MBProtocalFactory.createRecivedBack(pFromServer.to, pFromServer.from, pFromServer.fp);
            var code = MBDataSender.sendCommonData(pForRecivedBack);
            if (MBCore.debugEnabled()){
                console.log( "【QoS】向" + pFromServer.from + "发送" + pFromServer.fp + "包的应答包成功？(code=" + code + "),from=" + pFromServer.to + "！");
            }
        } else {
            console.log("【QoS】收到" + pFromServer.from + "发过来需要QoS的包，但它的指纹码却为null！无法发应答包！");
        }
    };



};

export default new MBDataReciever();